<?php
/**
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file license.txt or that can be found at 
 * http://code.google.com/p/billboardce/wiki/License.
 *
 * @package    Slidestream_IndexController
 * @category   Controller
 * @license    http://code.google.com/p/billboardce/wiki/License New BSD License
 * @version    SVN: $Id: $
 */

/**
 * Main controller for the application
 *
 * @package    Slidestream_IndexController
 * @category   Controller
 */
class SlidestreamController extends Zend_Controller_Action 
{   
          
    /**
     * Shows the slide streams that the user has created
     *
     */
    public function indexAction()
    {
        $this->view->acl = array(
           'details' => $this->_helper->hasAccess('details'),
           'delete'  => $this->_helper->hasAccess('delete')
       );
        
        $slidestream = new Slidestream();
        $slidestreamDevice = new Slidestream_Device();
        
        $slidestreams = $slidestream->getSlidestreamsForAccount(Zend_Auth::getInstance()->getIdentity()->accountId)->toArray();
        
        foreach ($slidestreams as &$s) {
            $s['devices'] = $slidestreamDevice->getDevicesForSlidestream($s['slidestreamId']);
        }
        
        $this->view->slidestreams = $slidestreams;
        
        $this->view->messages = $this->_helper->flashMessenger->getMessages();
        $this->_helper->pageTitle('slidestream-index-index:title');
    }
    
    /**
     * Lets the user create a new slide stream
     */
    public function addAction()
    {
        $slidestream = new Slidestream();
        
        $messages = array();
        
        $form = $slidestream->form();
                
        $data = array(
                    'accountId' => Zend_Auth::getInstance()->getIdentity()->accountId,
                    'title' => 'Untitled - ' . date('M j, Y')
                );
        
        $slidestreamId = $slidestream->insert($data);
                
        $this->_helper->redirector->gotoRoute(array('action' => 'details', 'slidestreamId' => $slidestreamId), 'slidestream', true);
    }
    
    /**
     * Deletes a slide stream
     */
    public function deleteAction()
    {
        $get = Zend_Registry::get('getFilter');
        
        if (!isset($get->slidestreamId)) {
            throw new Ot_Exception_Input('No slide steram ID given');
        }
        
        $slidestreamId = $get->slidestreamId;
        
        $slidestream = new Slidestream();
        
        $thisSlidestream = $slidestream->find($slidestreamId);
        
        if (is_null($thisSlidestream)) {
            throw new Ot_Exception_Data('Slide Stream not found');
        }
        
        if ($thisSlidestream->accountId != Zend_Auth::getInstance()->getIdentity()->accountId) {
            throw new Ot_Exception_Data('This does not appear to be your slide stream!');
        }
        
        $form = Ot_Form_Template::delete('deleteSlidestream');
        
        if ($this->_request->isPost() && $form->isValid($_POST)) {

            $slidestream->deleteSlidestream($slidestreamId);
            
            $this->_helper->flashMessenger->addMessage('Slide Stream deleted successfully');
            $this->_helper->redirector->gotoRoute(array(), 'slidestream', true);
        }
        
        $this->view->form = $form;
        $this->view->slidestream = $thisSlidestream;
    }
    
    /**
     * The main slide stream editor.  This is the bee's knees!
     */
    public function detailsAction()
    {
        $get = Zend_Registry::get('getFilter');
        
        if (!isset($get->slidestreamId)) {
            throw new Ot_Exception_Input('No slide steram ID given');
        }
        
        $redirect = $this->_getParam('redirect');
        
        // if there was a redirect, it's a device ID
        if (!is_null($redirect)) {
            $this->view->deviceRedirect = $redirect;
        }
        
        $slidestreamId = $get->slidestreamId;
        
        $slidestream = new Slidestream();
        
        $thisSlidestream = $slidestream->find($slidestreamId);
        
        if (is_null($thisSlidestream)) {
            throw new Ot_Exception_Data('Slide Stream not found');
        }
        
        if ($thisSlidestream->accountId != Zend_Auth::getInstance()->getIdentity()->accountId) {
            throw new Ot_Exception_Data('This does not appear to be your slide stream!');
        }
        
        $this->view->slidestream = $thisSlidestream;
        
        $slidestreamMap = new Slidestream_Slide();
        
        $slidePlugin = new Slide_Plugin();
        $slidestreamPlugin = new Slidestream_Plugin();
        $slidetype = new Slidetype();
        
        $this->view->slidePlugins = $slidePlugin->getEnabledPlugins();
        $this->view->slidestreamPlugins = $slidestreamPlugin->getEnabledPlugins();
        $this->view->slidetypes = $slidetype->getEnabledTypes();
        
        $this->view->messages = $this->_helper->flashMessenger->getMessages();

        $this->view->headScript()->appendFile('http://maps.google.com/maps/api/js?indexing=false&sensor=false');
        $this->view->headScript()->appendFile($this->view->baseUrl() . '/scripts/jquery.tmpl.min.js');
        $this->view->headScript()->appendFile($this->view->baseUrl() . '/scripts/jquery.plugin.json.js');
        $this->view->headScript()->appendFile($this->view->baseUrl() . '/scripts/jquery.plugin.cycle.js');
        $this->view->headScript()->appendFile($this->view->baseUrl() . '/scripts/iphone-style-checkboxes.js');
        $this->view->headLink()->appendStylesheet($this->view->baseUrl() . '/css/iphone-style-checkboxes.css');
        $this->view->headScript()->appendFile($this->view->baseUrl() . '/scripts/jscolor/jscolor.js');
        $this->view->headLink()->appendStylesheet($this->view->baseUrl() . '/scripts/jwysiwyg/jquery.wysiwyg.css');
        $this->view->headScript()->appendFile($this->view->baseUrl() . '/scripts/jwysiwyg/jquery.wysiwyg.js');
    }
    
    /**
     * Generates the list of unassigned devices 
     */
    public function getUnassignedDevicesAction()
    {
        $this->_helper->layout()->disableLayout();
        
        $device = new Device();
        $this->view->devices = $device->getUnassignedDevices(Zend_Auth::getInstance()->getIdentity()->accountId);   
    }
    
    /**
     * Assigns a device to a slide stream
     */
    public function assignDeviceAction()
    {
        $this->_helper->viewRenderer->setNeverRender();
        $this->_helper->layout()->disableLayout();
        
        if ($this->_request->isPost() && $this->_request->isXmlHttpRequest()) {
            
            $post = Zend_Registry::get('postFilter');
            
            if (!isset($post->slidestreamId)) {
                throw new Ot_Exception_Input('No slide stream ID given');
            }
            
            if (!isset($post->deviceId)) {
                throw new Ot_Exception_Input('No slide stream ID given');
            }
            
            $slidestreamId = $post->slidestreamId;
            
            $slidestream = new Slidestream();
            
            $thisSlidestream = $slidestream->find($slidestreamId);
            
            if (is_null($thisSlidestream)) {
                throw new Ot_Exception_Data('Slide stream not found');
            }
            
            $deviceId = $post->deviceId;
            
            if ($thisSlidestream->accountId != Zend_Auth::getInstance()->getIdentity()->accountId) {
                throw new Ot_Exception_Data('This does not appear to be your slide stream!');
            }
            
            $device = new Device();
            
            $thisDevice = $device->find($deviceId);
            
            if (is_null($thisDevice)) {
                throw new Ot_Exception_Data('Slide stream not found');
            }
            
            if ($thisDevice->accountId != Zend_Auth::getInstance()->getIdentity()->accountId) {
                throw new Ot_Exception_Data('This does not appear to be your device!');
            }
            
            $slidestreamDevice = new Slidestream_Device();
            
            $data = array('deviceId' => $deviceId, 'slidestreamId' => $slidestreamId);
            
            try {
                $slidestreamDevice->insert($data);
            } catch (Exception $e) {
                echo Zend_Json::encode(array('rc' => 0, 'msg' => 'Error assigning device: ' + $e->getMessage()));
                return;
            }
            
            echo Zend_Json::encode(array('rc' => 1, 'msg' => 'Device assigned successfully'));
            return;
        }
    }
    
    /**
     * Unassigns a device from a slide stream
     */
    public function unassignDeviceAction()
    {
        $this->_helper->viewRenderer->setNeverRender();
        $this->_helper->layout()->disableLayout();
        
        if ($this->_request->isPost() && $this->_request->isXmlHttpRequest()) {
            
            $post = Zend_Registry::get('postFilter');
            
            if (!isset($post->slidestreamId)) {
                throw new Ot_Exception_Input('No slide stream ID given');
            }
            
            if (!isset($post->deviceId)) {
                throw new Ot_Exception_Input('No slide stream ID given');
            }
            
            $slidestreamId = $post->slidestreamId;
            
            $slidestream = new Slidestream();
            
            $thisSlidestream = $slidestream->find($slidestreamId);
            
            if (is_null($thisSlidestream)) {
                throw new Ot_Exception_Data('Slide stream not found');
            }
            
            $deviceId = $post->deviceId;
            
            if ($thisSlidestream->accountId != Zend_Auth::getInstance()->getIdentity()->accountId) {
                throw new Ot_Exception_Data('This does not appear to be your slide stream!');
            }
            
            $device = new Device();
            
            $thisDevice = $device->find($deviceId);
            
            if (is_null($thisDevice)) {
                throw new Ot_Exception_Data('Slide stream not found');
            }
            
            if ($thisDevice->accountId != Zend_Auth::getInstance()->getIdentity()->accountId) {
                throw new Ot_Exception_Data('This does not appear to be your device!');
            }
            
            $slidestreamDevice = new Slidestream_Device();
            
            $where = $slidestreamDevice->getAdapter()->quoteInto('deviceId = ?', $deviceId)
                   . ' AND '
                   . $slidestreamDevice->getAdapter()->quoteInto('slidestreamId = ?', $slidestreamId);
            
            try {
                $slidestreamDevice->delete($where);
            } catch (Exception $e) {
                echo Zend_Json::encode(array('rc' => 0, 'msg' => 'Error unassigning device: ' + $e->getMessage()));
                return;
            }
            
            echo Zend_Json::encode(array('rc' => 1, 'msg' => 'Device unassigned successfully'));
            return;
        }
    }
    
    /**
     * Saves the structure for the slide stream
     */
    public function saveSlidestreamAction()
    {
        $post = Zend_Registry::get('postFilter');
        
        $data = Zend_Json::decode($_POST['data']);
        
        $slidestreamId = $post->slidestreamId;
        
        $slidestreamMap = new Slidestream_Slide();
        $slidestream = new Slidestream();
        
        $this->_helper->viewRenderer->setNeverRender();
        $this->_helper->layout()->disableLayout();
        
        $db = $slidestreamMap->getAdapter();
        
        $thisSlidestream = $slidestream->find($slidestreamId);
        
        if (is_null($thisSlidestream)) { 
            echo Zend_Json::encode(array('rc' => 0, 'msg' => 'Slide stream not found'));
            return;
        }
        
        if ($thisSlidestream->accountId != Zend_Auth::getInstance()->getIdentity()->accountId) {
            echo Zend_Json::encode(array('rc' => 0, 'msg' => 'This does not appear to be your slide stream'));
            return;
        }
                
        try {
            $slidestreamMap->saveSlidestream($slidestreamId, $data);            
        } catch (Exception $e) {
            echo Zend_Json::encode(array('rc' => 0, 'msg' => $e->getMessage()));
            return;
        }
        
        echo Zend_Json::encode(array('rc' => 1, 'msg' => 'Slide stream saved successfully!'));
    }
    
    /**
     * Returns the devices that are assigned to the slidestream as JSON
     */
    public function getDevicesAction()
    {
        $get = Zend_Registry::get('getFilter');
        
        if (!isset($get->slidestreamId)) {
            echo Zend_Json::encode(array('rc' => 0, 'msg' => 'No slide stream ID given'));
            return;
        }
        
        $slidestreamId = $get->slidestreamId;
        
        $slidestream = new Slidestream();
        $slidestreamDevice = new Slidestream_Device();
        
        $thisSlidestream = $slidestream->find($slidestreamId);
        
        if (is_null($thisSlidestream)) { 
            echo Zend_Json::encode(array('rc' => 0, 'msg' => 'Slide stream not found'));
            return;
        }
        
        if ($thisSlidestream->accountId != Zend_Auth::getInstance()->getIdentity()->accountId) {
            echo Zend_Json::encode(array('rc' => 0, 'msg' => 'This does not appear to be your slide stream'));
            return;
        }
        
        $devices = array();
        
        $devices = $slidestreamDevice->getDevicesForSlidestream($slidestreamId);
        
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNeverRender();
        
        echo Zend_Json::encode($devices);
    }
    
    /**
     * Returns the entities in a slidestream as JSON
     */
    public function getEntitiesAction()
    {
        $get = Zend_Registry::get('getFilter');
        
        if (!isset($get->slidestreamId)) {
            echo Zend_Json::encode(array('rc' => 0, 'msg' => 'No slide stream ID given'));
            return;
        }
        
        $slidestreamId = $get->slidestreamId;
        
        $slidestreamMap = new Slidestream_Slide();
        $slidestream = new Slidestream();
        
        $thisSlidestream = $slidestream->find($slidestreamId);
        
        if (is_null($thisSlidestream)) { 
            echo Zend_Json::encode(array('rc' => 0, 'msg' => 'Slide stream not found'));
            return;
        }
        
        if ($thisSlidestream->accountId != Zend_Auth::getInstance()->getIdentity()->accountId) {
            echo Zend_Json::encode(array('rc' => 0, 'msg' => 'This does not appear to be your slide stream'));
            return;
        }
        
        $entities = $slidestreamMap->getEntitiesForSlidestream($slidestreamId, true);
        
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNeverRender();
        
        echo Zend_Json::encode($entities);
    }
    
    /**
     * Returns the settings form for a given type of slide
     */
    public function getSlideSettingsFormAction()
    {
        
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNeverRender(true);
        
        $get = Zend_Registry::get('getFilter');
        
        if (!isset($get->type)) {
            $type = 'Url';
        } else {
            $type = $get->type;
        }
        
        $typeObj = Slidetype::factory($type);
        
        echo 'Slidetype: ' . $typeObj->getTitle() . $typeObj->getConfigurationForm();
    }
    
    /**
     * Checks to see if a set of screenshots exist for a given slide ID
     *
     * @return JSON Returns an object with true or false based on whether or not the screenshots exist
     */
    public function screenshotsExistAction()
    {
    	
        $get = Zend_Registry::get('getFilter');
        
        if (!isset($get->slideId)) {
            throw new Exception('Slide ID not set in query string');
        }
        
        $screenshotPath = realpath(APPLICATION_PATH . '/../public/screenshots');
        
        if (!is_dir($screenshotPath . '/' . $get->slideId)) {
            mkdir($screenshotPath . '/' . $get->slideId);
        }
        
        $previewImage = $screenshotPath . '/' . $get->slideId . '/source.jpg';
        
        // check to see if source exists.  if it does, so should the others
        if ((file_exists($previewImage))) {
            echo Zend_Json::encode(array('result' => '1'));
        } else {
        	echo Zend_Json::encode(array('result' => '0'));
        }
        
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNeverRender();
    }
}